import os
from PIL import Image
import numpy as np
from tqdm import tqdm


def black2white(img_path_origin: str):
    """
    将黑色图片转换为白色图片的函数，方便打印（忽略白色图片）

    :param img_path_origin: 输入路径；若是文件，则直接转换；若是文件夹，则将文件夹下的图片都进行转换；
    :return:
    """
    appendix = {'.jpg', '.png'}
    img_paths = []
    if os.path.isdir(img_path_origin):
        for name in os.listdir(img_path_origin):
            img_path_inner = f'{img_path_origin}/{name}'
            if not os.path.isdir(img_path_inner) and os.path.splitext(img_path_inner)[1] in appendix:
                img_paths.append(img_path_inner)
    else:
        img_paths = [img_path_origin]
    length = len(img_paths)
    for i in tqdm(range(length)):
        path = img_paths[i]
        img_path_output = f'{os.path.splitext(path)[0]}_output.jpg'
        img_origin = Image.open(path)
        img_gray = img_origin.convert('L')
        img_gray_array = np.asarray(img_gray)
        if np.mean(img_gray_array) < 127.5:
            img_gray_array_minus = 255 - img_gray_array
            img_gray_minus = Image.fromarray(img_gray_array_minus)
            img_gray_minus.save(img_path_output)
